iT邦幫忙

1

[ JS個人筆記 ] 閉包Closure—DAY6

  • 分享至 

  • xImage
  •  
  • 簡單來說,就是呼叫函式內的函式,將記憶體封存在內層。

  • 像這樣,我們把 count 封裝在 counter() 當中,不但可以讓裡面的 count 不會暴露在 global 環境造成變數衝突,也可以確保內部 count 被修改。

function counter(){
  var count = 0;

  function innerCounter(){
    return ++count;
  }

  return innerCounter;
}

var countFunc = counter();

console.log( countFunc() );   // 1
console.log( countFunc() );   // 2
console.log( countFunc() );   // 3
  • 外值得一提的是,過去我們需要新增另一個計數器時,可能會再新增另一個全域變數去儲存另一個 count 的狀態。 而改用閉包的寫法之後,只需要像這樣:
  • 此時你就會發現 countFunc 與 countFunc2 分別是「獨立」的計數器實體,彼此不會互相干擾!
function counter(){
  var count = 0;

  return function(){
    return ++count;
  }
}

var countFunc = counter();
var countFunc2 = counter();

console.log( countFunc() );   // 1
console.log( countFunc() );   // 2
console.log( countFunc() );   // 3

console.log( countFunc2() );   // 1
console.log( countFunc2() );   // 2
  • Closure常見應用

function callMethod(newMoney) {
  var money = newMoney || 1000;
  return function (price) {
    money = money - price;
    return money;
  }
}
let updateMyMoney = callMethod(10000000000);
let updateYourMoney = callMethod(1000);
console.log(updateMyMoney(100));
console.log(updateYourMoney(100));
  • 實現 private
    =>使用閉包來定義公共函數,且其可以訪問私有函數和變數,這個方式也稱為模組模式(module pattern)。
/*自調用函數,共用生存域*/
function Counter() {
  let innerCounter = 0;
  function change(val) {
    innerCounter += val;
  }
  return {
    addone: function() {
      change(1);
    },
    deone: function() {
      change(-1);
    },
    value: function() {
      return innerCounter;
    }
  }
}

let newCounter = Counter()
console.log(newCounter.value()); /* logs 0 */

newCounter.addone();
newCounter.addone();

console.log(newCounter.value()); /* logs 2 */

newCounter.deone();

console.log(newCounter.value()); /* logs 1 */

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言